package com.cqgc.utils;

import com.alibaba.excel.write.handler.CellWriteHandler;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.excel.EasyExcel;
import org.apache.poi.ss.usermodel.*;

import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.IndexedColors;

@Slf4j
public class ExcelUtil {

    // ... 其他原有方法 ...

    /**
     * 使用EasyExcel导出数据到OutputStream。
     *
     * @param outputStream 输出流
     * @param sheetName    工作表名称
     * @param data         数据列表
     * @param clazz        实体类类型
     */
    public static <T> void exportDataWithEasyExcel(OutputStream outputStream, String sheetName, List<T> data, Class<T> clazz) {
        try {
            // 定义写入样式，这部分逻辑保持不变
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            // 设置默认边框
            contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
            contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
            contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
            contentWriteCellStyle.setBorderTop(BorderStyle.THIN);

            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            headWriteCellStyle.setBorderBottom(BorderStyle.THIN);
            headWriteCellStyle.setBorderLeft(BorderStyle.THIN);
            headWriteCellStyle.setBorderRight(BorderStyle.THIN);
            headWriteCellStyle.setBorderTop(BorderStyle.THIN);

            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

            // 修改为使用OutputStream
            EasyExcel.write(outputStream, clazz)
                    .registerWriteHandler(horizontalCellStyleStrategy) // 注意类型转换，确保兼容性
                    // 如果有自定义日期格式或其他转换需求，可以在这里注册Converter
                    .sheet(sheetName)
                    .doWrite(data);
        } catch (Exception e) {
            log.error("Failed to export data to OutputStream", e);
            throw new RuntimeException("Failed to export data to OutputStream", e);
        }
    }
}

